package com.hmkj.admin.controller.operate;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hmkj.admin.controller.BaseController;
import com.hmkj.admin.controller.GenericController;
import com.hmkj.admin.utils.AdminSessionHelper;
import com.hmkj.common.baseMapper.GenericPo;
import com.hmkj.common.entity.ResultEntity;
import com.hmkj.common.entity.dtgrid.DtGrid;
import com.hmkj.common.utils.StringUtils;
import com.hmkj.core.exception.BussinessException;
import com.hmkj.core.model.operate.AgentModel;
import com.hmkj.core.po.operate.Agent;
import com.hmkj.core.po.operate.AgentConfig;
import com.hmkj.core.po.system.Admin;
import com.hmkj.core.service.operate.AgentConfigService;
import com.hmkj.core.service.operate.AgentService;
import com.hmkj.core.service.system.AdminService;
import lombok.extern.log4j.Log4j;
import net.sf.json.JSONObject;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.xml.transform.OutputKeys;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@Log4j
@Controller
@RequestMapping(BaseController.BASE_URI)
public class AgentJsonController extends GenericController<Integer, Agent> {

    @Resource
    private AgentService agentService;
    @Resource
    private AgentConfigService agentConfigService;
    @Resource
    private AdminService adminService;


    /**
     *  代理商列表json数据
     * @param dtGridPager
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("agent/json/list")
    @RequiresPermissions("sys:agent:list")
    public DtGrid listJson(String dtGridPager) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        DtGrid dtgrid = mapper.readValue(dtGridPager, DtGrid.class);
        Map<String, Object> parameters = dtgrid.getFastQueryParameters();
        Admin admin = AdminSessionHelper.getCurrAdmin();
        if(admin.getType()==Admin.TYPE.T3.code){
            parameters.put("eq_id",admin.getBussId());
            dtgrid.setFastQueryParameters(parameters);
        }
        dtgrid  =  agentService.getDtGridList(dtgrid);
        if( dtgrid.getExhibitDatas()!=null &&  dtgrid.getExhibitDatas().size()>0){
            List<Object> objects =  new ArrayList<>();
            for (Object obj : dtgrid.getExhibitDatas()) {
                LinkedHashMap map = (LinkedHashMap) obj;
                List<AgentConfig> acLIst = agentConfigService.select(new AgentConfig(ac->{
                    ac.setAgentId((Integer) map.get("id"));
                    ac.setDelFlag(AgentConfig.DELFLAG.NORMAL.code);
                }));
                if(acLIst!=null&&acLIst.size()>0){
                    acLIst.forEach(ac->{
                        if(ac.getNid().equals("gc_fee")){
                            map.put("gcFee",ac.getValue());
                        }else if(ac.getNid().equals("cl_fee")){
                            map.put("clFee",ac.getValue());
                        }else if(ac.getNid().equals("si_fee")){
                            map.put("siFee",ac.getValue());
                        }else if(ac.getNid().equals("hsi_fee")){
                            map.put("hsiFee",ac.getValue());
                        }else if(ac.getNid().equals("mhi_fee")){
                            map.put("mhiFee",ac.getValue());
                        }else if(ac.getNid().equals("dax_fee")){
                            map.put("daxFee",ac.getValue());
                        }
                    });
                }
                objects.add(map);
            }
            dtgrid.setExhibitDatas(objects);
        }
        return dtgrid;
    }

    /**
     * 新增代理商
     * @param agentModel
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("agent/json/save")
    @RequiresPermissions("sys:agent:save")
    public ResultEntity addJson(AgentModel agentModel) throws  Exception{
        String result = checkModel(agentModel);
        if(result!=null) {
            throw new BussinessException(result);
        }
        String result1 = checkRepeat(agentModel);
        if(result1!=null){
            throw new BussinessException(result1);
        }
        Agent agent = agentService.selectAgentByDomain(agentModel.getDomain());
        if(agent!=null){
            throw new BussinessException("代理商域名已存在");
        }
        agentModel = retainDecimal(agentModel);
        agentService.addAgent(agentModel);
        return ok();
    }

    /**
     * 编辑代理商
     * @param agentModel
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("agent/json/edit")
    @RequiresPermissions("sys:agent:edit")
    public ResultEntity editJson(AgentModel agentModel) throws  Exception{
        String result = checkModel(agentModel);
        if(result!=null) {
            throw new BussinessException(result);
        }
        String result1 = checkRepeat(agentModel);
        if(result1!=null){
            throw new BussinessException(result1);
        }
        Agent agent = agentService.selectAgentByDomain(agentModel.getDomain());
        if(agent!=null && agentModel.getId() != agent.getId()){
            throw new BussinessException("代理商域名已存在");
        }
        agentModel = retainDecimal(agentModel);
        agentService.editAgent(agentModel);
        return ok();
    }



    /**
     *  删除代理商
     * @param id
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("agent/json/del")
    @RequiresPermissions("sys:agent:del")
    public ResultEntity delJson(Integer id) throws Exception {
        if(id ==null){
            throw new BussinessException("参数错误！");
        }
        Agent agent = new Agent();
        agent.setId(id);
        agent.setDelFlag(Agent.DELFLAG.NORMAL.code);
        Agent age = agentService.selectByPrimaryKey(id);
        if (null == age) {
            throw new BussinessException("代理商不存在！");
        }
        agentService.deleteAgent(id);
        return ok();
    }

    private AgentModel retainDecimal(AgentModel agentModel) {
        agentModel.setName(agentModel.getName().trim());
        agentModel.setCode(agentModel.getCode().trim());
        agentModel.setDomain(agentModel.getDomain().trim());
        agentModel.setSmsSign(agentModel.getSmsSign().trim());
        agentModel.setFullName(agentModel.getFullName().trim());
        //保留2位小数且四舍五入
        if(StringUtils.isNotBlank(agentModel.getGcFee())){
            agentModel.setGcFee(agentModel.getGcFee().setScale(2, BigDecimal.ROUND_HALF_DOWN));
        }
        if(StringUtils.isNotBlank(agentModel.getClFee())){
            agentModel.setClFee(agentModel.getClFee().setScale(2, BigDecimal.ROUND_HALF_DOWN));
        }
        if(StringUtils.isNotBlank(agentModel.getSiFee())){
            agentModel.setSiFee(agentModel.getSiFee().setScale(2, BigDecimal.ROUND_HALF_DOWN));
        }
        if(StringUtils.isNotBlank(agentModel.getHsiFee())){
            agentModel.setHsiFee(agentModel.getHsiFee().setScale(2, BigDecimal.ROUND_HALF_DOWN));
        }
        if(StringUtils.isNotBlank(agentModel.getMhiFee())){
            agentModel.setMhiFee(agentModel.getMhiFee().setScale(2, BigDecimal.ROUND_HALF_DOWN));
        }
        if(StringUtils.isNotBlank(agentModel.getDaxFee())){
            agentModel.setDaxFee(agentModel.getDaxFee().setScale(2, BigDecimal.ROUND_HALF_DOWN));
        }
        return agentModel;
    }


    private String checkModel(AgentModel agentModel){
        String result = null;
        String str  = "^[\\u005b\\u005d\\uff08\\uff09\\u0029\\u0028\\u0020\\：\\:\\%\\_\\,\\，\\.\\!\\！\\【\\】\\u4e00-\\u9fa5\\-a-zA-Z0-9]+$";
        String str1  = "^[\\-a-zA-Z0-9]+$";
        String str3  = "^[\\u0026\\u002b\\u003d\\uff1f\\u005f\\u002f\\u005b\\u005d\\u0029\\u0028\\u0020\\：\\:\\%\\_\\,\\，\\.\\!\\！\\-a-zA-Z0-9]+$";

        String mail1  = agentModel.getName();
        String mail2  = agentModel.getCode();
        String mail3  = agentModel.getFullName();
        String mail4  = agentModel.getDomain();
        String mail5  = agentModel.getSmsSign();
        if (!StringUtils.isNotBlank(agentModel.getName())){
            result = "代理商名称不能为空";
        }else if (!StringUtils.isNotBlank(agentModel.getCode())){
            result = "代理商id不能为空";
        }else if (!StringUtils.isNotBlank(agentModel.getFullName())){
            result = "代理商协议名称不能为空";
        }else if (!StringUtils.isNotBlank(agentModel.getDomain())){
            result = "代理商域名不能为空";
        }else if (!StringUtils.isNotBlank(agentModel.getSmsSign())){
            result = "代理商短信签名不能为空";
        }else if (agentModel.getName().length()>100) {
            result = "代理商名称不能超过100个字符";
        }else if (!mail1.matches(str)) {
            result = "代理商名称不能包含其他特殊符号";
        }else if (!mail2.matches(str1)) {
            result = "代理商ID不能包含特殊符号与中文";
        }else if (agentModel.getFullName().length()>100) {
            result = "代理商协议名称不能超过100个字符";
        }else if (!mail3.matches(str)) {
            result = "代理商协议名称不能包含其他特殊符号";
        }else if (agentModel.getDomain().length()>200) {
            result = "代理商域名不能超过200个字符";
        }else if (!mail4.matches(str3)) {
            result = "代理商域名不能包含其他特殊符号";
        }else if (agentModel.getSmsSign().length()>10) {
            result = "代理商短信签名不能超过10个字符";
        }else if (!mail5.matches(str)) {
            result = "代理商短信签名不能包含其他特殊符号";
        }
        return result;
    }


    /**
     * 重复校验
     * @param agentModel
     * @return
     * @throws Exception
     */
    private  String checkRepeat(AgentModel agentModel) throws Exception{
        String result = null;
        List<Agent> agents =  agentService.select(new Agent(a->{
            a.setCode(agentModel.getCode());
        }));
        List<Agent> agents1 =  agentService.select(new Agent(a->{
            a.setName(agentModel.getName());
        }));
        List<Agent> agents2 =  agentService.select(new Agent(a->{
            a.setDomain(agentModel.getDomain());
        }));
        if(agents.size()>0){
            if(agentModel.getId() !=null){
                for (Agent agent:agents){
                    if(agent.getId()!=agentModel.getId()){
                        result = "代理商id已存在";
                    }
                }
            }else{
                result = "代理商id已存在";
            }
        }else if (agents1.size()>0){
            if(agentModel.getId() !=null) {
                for (Agent agent:agents1){
                    if(agent.getId()!=agentModel.getId()){
                        result = "代理商名称已存在";
                    }
                }
            }else{
                result = "代理商名称已存在";
            }
        }else if (agents2.size()>0) {
            if (agentModel.getId() != null) {
                for (Agent agent : agents1) {
                    if (agent.getId() != agentModel.getId()) {
                        result = "代理商域名已存在";
                    }
                }
            } else {
                result = "代理商域名已存在";
            }
        }
        return result;
    }

    /**
     * 绑定后台的管理员列表json数据
     * @param dtGridPager
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("agent/json/adminList")
//    @RequiresPermissions("sys:agent:adminList")
    public DtGrid adminListJson(String dtGridPager) throws  Exception{
        DtGrid dtgrid  =  adminService.getDtGridList(dtGridPager);
        return dtgrid;
    }

    /**
     * 查可绑定后台的代理商列表
     * @param dtGridPager
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("agent/josn/bindList")
//    @RequiresPermissions("sys:agent:list")
    public DtGrid bindListJson(String dtGridPager) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        DtGrid dtgrid = mapper.readValue(dtGridPager, DtGrid.class);
//        Map<String, Object> parameters = dtgrid.getFastQueryParameters();
//        List<Admin> admins =  adminService.select(new Admin(a->{
//            a.setType(Admin.TYPE.T3.code);
//            a.setDelFlag(Admin.DELFLAG.NORMAL.code);
//        }));
//        String userIds = "0";
//        if (admins != null && admins.size() > 0) {
//            userIds = admins.stream().map(param -> param.getBussId().toString()).collect(Collectors.joining(","));
//        }
//        parameters.put("nin_id",userIds);
//        dtgrid.setFastQueryParameters(parameters);
        dtgrid = agentService.getDtGridList(dtgrid);
        return dtgrid;
    }

        /**
         * 解除代理商绑定管理员
         *
         * @param id
         * @return
         * @throws Exception
         */
    @ResponseBody
    @RequestMapping("agent/json/cancel")
    @RequiresPermissions("agent:bind:cancel")
    public ResultEntity adminDelJson(Integer id) throws Exception {
        Admin adm = adminService.selectByPrimaryKey(id);
        if (null == adm ) {
            throw new BussinessException("绑定的后台管理员不存在！");
        }
        Admin admin = new Admin();
        admin.setId(id);
        admin.setDelFlag(Admin.DELFLAG.DELETED.code);
        adminService.updateByPrimaryKeySelective(admin);
        return ok();
    }



}
